import { useCounterStore } from '@/stores/index.js'; 
const url = import.meta.env.VITE_WS;

const WS = {
  $ws: null, // webscoket实例
  wsUrl: url, // websocket链接地址
  timeout: 30000, // 心跳重连时间
  timeoutObj: null, // 定时器
  lockReconnect: false, // 避免重复重连
  reconnectTimes: 0, // 重连次数
  connected: false,

  // 初始化webSocket
  createWS: function () {
    if ("WebSocket" in window) {
      let url = WS.wsUrl;

      url += "?paramterType=" + "user" + "&id=" + `${110}`;

      console.log("wsurl ", url);
      this.$ws = new WebSocket(url);
      this.$ws.onopen = this.wsOpen;
      this.$ws.onmessage = this.wsMessage;
      this.$ws.onerror = this.wsError;
      this.$ws.onclose = this.wsClose;
    } else {
      alert("Current browser Not support websocket");
    }
  },
  // webSocket 打开
  wsOpen: function () {
    // store.dispatch("websocket/setConnect", true);
    console.log("== websocket open ==");
    WS.connected = true;
    WS.wsSend("PING");
    // <!--开始心跳-->
    heartBeat.start();
  },
  // websocket 接收到服务器消息
  wsMessage: function (msg) {
    if (msg.data === "PONG") {
      // 每次接收到服务端消息后 重置websocket心跳
      WS.wsRset();
    } else {
      try {
        const res = JSON.parse(msg.data);
        if (res.code === "200") {
			
			const counterStore = useCounterStore();
			counterStore.setPot(res.message)
			
          // store.dispatch("listgroup/setListGroup", res.message);
        }
      } catch (e) {
        console.log(e);
      }
    }
  },
  // websocket 发生错误
  wsError: function (err) {
    console.log("== websocket error ==", err);
    // 发生错误重连socket
    if (WS.reconnectTimes < 10) {
      WS.connected = false;
      WS.wsReconnect();
    }
  },
  // websocket 关闭连接
  wsClose: function () {
    console.log("== websocket close ==");
    WS.connected = false;
    if (WS.$ws && WS.$ws.readyState === 1) {
      WS.$ws.close();
     
    }
    WS.wsReconnect();

    // if (hasToken) {
    if (WS.reconnectTimes < 10) {
      // 设置重连次数为10次
      WS.wsReconnect();
    }
    // }
  },
  // socket开始心跳
  wsStartHeart: function () {
    WS.timeoutObj && clearTimeout(WS.timeoutObj);
    WS.timeoutObj = setTimeout(function () {
      // 判断websocket当前状态
      WS.wsSend("PING");
    }, WS.timeout);
  },
  // socket 重置心跳
  wsRset: function () {
    clearTimeout(WS.timeoutObj);
    WS.wsStartHeart();
  },
  // socket 重连
  wsReconnect: function () {
    console.log("Reconnection Socket ", WS.lockReconnect);
    if (WS.lockReconnect) return;
    // WS.reconnectTimes++
    WS.lockReconnect = true;
    setTimeout(function () {
      // 没连接上会一直重连，设置延迟避免请求过多

      WS.createWS();
      WS.lockReconnect = false;
    }, 6000);
  },
  wsSend: function (msg) {
    console.log("wsSend ", msg);
    if (WS.$ws.readyState === 1) {
      WS.$ws.send(msg);
    }
  },
};
const heartBeat = {
  timeout: 30000, // 心跳重连时间
  timeoutObj: null, // 定时器
  reset: function () {
    clearTimeout(this.timeoutObj);
    heartBeat.start();
  },
  start: function () {
    if (this.timeoutObj) {
      clearTimeout(this.timeoutObj);
      this.timeoutObj = null;
    }
    this.timeoutObj = setTimeout(function () {
      WS.wsSend("PING");
    }, this.timeout);
  },
};
export default WS;
